/**
 * MIT License
 * 
 * Copyright (c) 2024 - present @ ebraid
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <types.h>
#include <stdio.h>
#include <string.h>

/**
 * @brief Convert a string to a long integer.
 * @param s The string to convert.
 * @return The converted long integer.
 * @note This function converts a string to a long integer. It handles negative numbers and skips leading whitespace.
 */
long atol(const char *s)
{
    long n = 0;
    int neg = 0;

    // Skip leading whitespace
    while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\v' || *s == '\f' || *s == '\r') 
        s++;

    // Handle optional sign
    if (*s == '-') {
        neg = 1;
        s++;
    } else if (*s == '+') {
        s++;
    }

    // Convert digits to integer
    while (*s >= '0' && *s <= '9') {
        n = n * 10 + (*s - '0');
        s++;
    }

    return neg ? -n : n;
}


int __aeabi_idiv(int numerator, int denominator) {
    int result = 0;
    int sign = 1;

    // 处理负数
    if (numerator < 0) {
        numerator = -numerator;
        sign = -sign;
    }
    if (denominator < 0) {
        denominator = -denominator;
        sign = -sign;
    }

    // 快速除法
    if (denominator != 0) {
        while (numerator >= denominator) {
            int temp_den = denominator;
            int temp_res = 1;
            while (numerator >= (temp_den << 1)) {
                temp_den <<= 1;
                temp_res <<= 1;
            }
            numerator -= temp_den;
            result += temp_res;
        }
    }

    // 返回结果
    return sign * result;
}
